home *** CD-ROM | disk | FTP | other *** search
- Path: titan.fullerton.edu!grosin
- From: grosin@titan.fullerton.edu (Gil Rosin)
- Newsgroups: comp.lang.c++
- Subject: Please help w/ Stack implementation
- Date: 3 Mar 1996 06:32:40 GMT
- Organization: California State University at Fullerton
- Message-ID: <4hbee8$b6h@wintermute.ecs.fullerton.edu>
- NNTP-Posting-Host: titan.ecs.fullerton.edu
- X-Newsreader: TIN [version 1.2 PL2]
-
- Hi, I'm learning C++ and am doing a Stack class to help learn some features of
- C++. I am using templates for generic a generic stack.
-
- I am also using reference functions for Pop() and TopElement() which pop and
- return the top element as well as just return the top element respectively.
-
- Now, currently, my "node record" is defined as:
-
- struct Node
- {
- ElementType Element;
- Node *Next;
- };
-
- Now, for TopElement, its simple, I just return the crap at the head of the
- stack and don't have to worry about it going out of existance.
-
- But how do I handle Pop()?
-
- Currently I have it defined as:
-
- template <class ElementType>
-
- ElementType & Stack<ElementType>::Pop()
-
- {
-
- Node *TempNode; //
-
- ElementType & TempElement = TopOfStack->Element; //
-
-
-
- cout << &TempElement << '\n';
-
- cout << &TopOfStack->Element << '\n';
-
- //
-
- if (ElementsInStack) //
-
- { //
-
- TempNode = TopOfStack->NextNode; //
-
- delete TopOfStack; //
-
- TopOfStack = TempNode; //
-
- ElementsInStack--; //
-
- return TempElement; //
-
- } //
-
- else //
-
- cout << "Error: Stack is empty." << '\n'; //
-
- return TempElement; //
-
- }
-
-
- Ok, now as you can see in this function. I return TempElement at the end,
- this is incorrect right? Since the damn thing is DELETED!
-
- How can I handle this? I thought about having TempElement as a pointer
- instead, but then I have a stray memory allocation lying around. Lets say I
- went this route, how would I clean up all the allocated memory left over
- from popping the items?
-
- I also looked at Borland C++'s stack class and they have a Node record
- declared somewhat like mine, except Element is a pointer and each element
- is allocated memory.
-
- Then when they pop it, they detach it from the list, they delete the actual
- node record, but leave the element allocated. So again, you have stray
- memory left over.
-
- Now my question is how do I handle that allocated memory from elements if I
- don't delete them, but delete the only pointer to them and remove them from
- the stack?
-
- Of course the user can delete them, but that is a cumbersome chore, I mean,
- if I wanted to simply print out the value, I would need minimum two lines,
- one to Read the element with TopElement and one to pop it with Pop.
-
- Can some one give me some information on this, like I said, I am new to C++,
- so I might be missing where the clean up is done and how.
-
- P.S., this is NOT homework, I am doing this for myself.
-
- Please reply via email to grosin@titan.fullerton.edu
-
-
-